'use strict';
const Service = require('egg').Service;

class AdminService extends Service {
  async findAll() {
    const users = await this.app.mysql.query('select * from admin where is_delete = 0');
    return users;
  }
  // 获取详情数据
  async getAdminDetail(id) {
    const user = await this.app.mysql.get('admin', { id });
    return user;
  }
  // 新增管理员
  async addAdmin(data) {
    // console.log('addAdmin data:', data);
    const res = await this.app.mysql.insert('admin', data);
    // console.log('res:', res);
    if (res.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };

  }
  // 删除管理员
  async deleteAdmin(id) {
    // console.log('id:', id);
    const res = await this.app.mysql.delete('admin', { id });
    // console.log('res:', res);
    if (res.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };
  }
  // 修改密码
  async updateAdmin(data) {
    // console.log('data:', data);
    if (data.username) {
      const dResult = await this.app.mysql.get('admin', { username: data.username });
      // console.log('updateAdmin dResult:', dResult);
      if (dResult && dResult.id !== +data.id) {
        return {
          code: -2,
        };
      }
    }
    const res = await this.app.mysql.update('admin', data);
    // console.log('res:', res);
    if (res.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };


  }
}

module.exports = AdminService;
